import React,{ Component } from 'react'
import { Form, Input, Button, Spin, Checkbox, message } from 'antd'
import { connect } from 'dva'
import { Link } from 'umi'
import styles from './index.css'
import FormTitle from '../FormTitle'

const FormItem = Form.Item;

class RegisterForm extends Component {

    constructor(props){
        super(props);
        this.state = {
            confirmDirty: false
        };
        this.isOnBluring = false;
        this.form = this.props.form;
        this.dispatch = this.props.dispatch;
    }


    handleSubmit = (e) => {
        e.preventDefault();
        this.form.validateFields((err, values)=>{
            if(!err){
                const {confirmPwd,...rest} = values;
                this.dispatch({
                    type: 'auth/register',
                    payload: {
                        ...rest
                    }
                }).then( res =>{
                    if(res.code === 0){
                        message.success('注册成功');
                        this.props.onClick()
                    }else{
                        message.error('注册失败')
                    }
                })
            }
        })
    };

    handleBlur = (e, type) => {
        const value = e.target.value;
        switch (type){
            case 'username':
                this.isOnBluring = true;
                this.props.form.validateFields(['username'], { force: true });
                break;
            case 'confirmPwd':
                this.setState({ confirmDirty: this.state.confirmDirty || !!value });
                break;
            default:
        }
    };

    /**
     * 校验回调接口：校验用户名是否已经存在
     * @param rule
     * @param value
     * @param callback
     */
    confirmUsername = (rule, value, callback) => {
        if(!this.isOnBluring){
            callback();
            return;
        }
        const form = this.form;
        if(!form.getFieldError('username') && value){
            this.props.dispatch({
                type: 'auth/confirmName',
                payload: {
                    username: value
                }
            }).then((res)=>{
                if(res.code === 0){
                    callback();
                }else{
                    callback('用户名已存在');
                    // this.props.form.setFields({username:{value:value,errors:[new Error()]}})
                }
            });
        }
        this.isOnBluring = false;
    };

    /**
     * 校验回调接口：强制让ConfirmPwd进行校验
     * @param rule
     * @param value
     * @param callback
     */
    validateToConfirmPwd = (rule, value, callback) => {
        const form = this.form;
        if (value && this.state.confirmDirty) {
            form.validateFields(['confirmPwd'], { force: true });
        }
        callback();
    };

    /**
     * 校验回调接口：校验确认密码与密码是否一致
     * @param rule
     * @param value
     * @param callback
     */
    compareToPassword = (rule, value, callback) => {
        const form = this.form;
        if (value && value !== form.getFieldValue('password')) {
            callback('与密码不一致');
        } else {
            callback();
        }
    };

    validatorReadMe = (rule, value, callback) => {
        value?callback():callback('需同意服务条款才能注册')
    }

    render() {
        const { getFieldDecorator } = this.props.form;
        const formItemLayout = {
            wrapperCol: {
                md: { span: 24 }
            }
        };
        return (
            <div className={`${this.props.className} ${styles.wrapper}`} style={this.props.style}>
                <Spin spinning={this.props.loading}>
                    <Form {...formItemLayout} onSubmit={this.handleSubmit} className={styles.register_form}>
                        <FormTitle title={'注册界面'}/>
                        <FormItem hasFeedback >
                            {
                                getFieldDecorator('username',
                                    {
                                        rules: [
                                            {
                                                validateTrigger:'onChange',
                                                required: true,
                                                message: '用户名不能为空',
                                            },{
                                                validateTrigger:'onChange',
                                                min: 4,
                                                max: 12,
                                                message: '长度必须控制在在4-12范围内',
                                            },{
                                                validator: this.confirmUsername
                                            }
                                        ]
                                    }
                                )(
                                    <Input placeholder={'请输入用户名（必填）'} onBlur={(e)=>this.handleBlur(e,'username')}/>,
                                )
                            }
                        </FormItem>
                        <FormItem hasFeedback>
                            {
                                getFieldDecorator('password',
                                    {
                                        validateFirst: true,
                                        rules: [
                                            {
                                                required: true,
                                                message: '密码不能为空',
                                            },{
                                                validator: this.validateToConfirmPwd,
                                            },{
                                                min: 6,
                                                max: 16,
                                                message: '密码长度必须控制在6-16范围内',
                                            }
                                        ]
                                    }
                                )(
                                    <Input type={'password'} placeholder={'请输入密码（必填）'}/>,
                                )
                            }
                        </FormItem>
                        <FormItem hasFeedback>
                            {
                                getFieldDecorator('confirmPwd',
                                    {
                                        validateFirst: true,
                                        rules: [
                                            {
                                                required: true,
                                                message: '确认密码不能为空',
                                            },{
                                                validator: this.compareToPassword,
                                            },{
                                                min: 6,
                                                max: 16,
                                                message: '密码长度必须控制在6-16范围内',
                                            }
                                        ]
                                    }
                                )(
                                    <Input type={'password'} placeholder={'请输入确认密码（必填）'} onBlur={(e)=>this.handleBlur(e,'confirmPwd')}/>,
                                )
                            }
                        </FormItem>
                        <FormItem hasFeedback>
                            {
                                getFieldDecorator('registerCode',
                                    {
                                        rules: [
                                            {
                                                required: true,
                                                message: '注册码不能为空',
                                            }, {
                                                max: 40,
                                                message: '注册码长度必须控制在40以内',
                                            },
                                        ]
                                    }
                                )(
                                    <Input type={'password'} placeholder={'请输入注册码（必填）'}/>,
                                )
                            }
                        </FormItem>
                        <FormItem>
                            {
                                getFieldDecorator('readme',
                                    {
                                        initialValue: false,
                                        valuePropName: 'checked',
                                        rules: [
                                            {
                                                required: true,
                                                message: '需同意服务条款才能注册'
                                            },{
                                                validator: this.validatorReadMe
                                            }
                                        ]
                                    }
                                )(
                                    <Checkbox>我已经阅读<Link to={'/auth/readme'} target={'_blank'}>《服务条款》</Link></Checkbox>
                                )
                            }
                        </FormItem>
                        <Button className={styles.register_button} type={'primary'} htmlType={'submit'}>注册</Button>
                        <Button className={styles.return} type={'primary'} onClick={this.props.onClick}>返回</Button>
                    </Form>
                </Spin>
            </div>
        );
    }
}

export default connect(
    ({loading})=>{
        return {
            loading: !!loading.models.auth
        }
    },null)(Form.create({})(RegisterForm))
